package com.assets.Fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.Scan.qrcode.util.Constant;
import com.assets.Scan.zxing.activity.CaptureActivity;
import com.assets.menu.SlideSideMenuExampleActivity;
import com.assets.util.TrustAllCerts;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Administrator on 2019/5/18.
 */

public class Seek extends Fragment {
    private ImageView opmenu;
    private ImageView scan_img, is_image;
    private String url = "http://" + Url.IP + "/api/assetScanQuery";
    private SlideSideMenuExampleActivity content;
    private TextView odd, grundlagen, createdate, AssetNumber, AssetName, DeptId, custodian, model, Type, status, place;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.seek_function, null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        content = (SlideSideMenuExampleActivity) getActivity();
        inview();
        scan_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQrCode();
            }
        });

        opmenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SlideSideMenuTransitionLayout mSlideSideMenu = (SlideSideMenuTransitionLayout) getActivity().findViewById(R.id.slide_side_menu);
                mSlideSideMenu.toggle();
            }
        });


    }

    private void inview() {
        odd = (TextView) content.findViewById(R.id.odd);
        grundlagen = (TextView) content.findViewById(R.id.grundlagen);
        createdate = (TextView) content.findViewById(R.id.createdate);
        is_image = (ImageView) content.findViewById(R.id.is_image);
        opmenu = (ImageView) content.findViewById(R.id.opmenu);
        place = (TextView) content.findViewById(R.id.place);
        status = (TextView) content.findViewById(R.id.status);
        Type = (TextView) content.findViewById(R.id.Type);
        model = (TextView) content.findViewById(R.id.model);
        custodian = (TextView) content.findViewById(R.id.custodian);
        DeptId = (TextView) content.findViewById(R.id.DeptId);
        AssetName = (TextView) content.findViewById(R.id.AssetName);
        scan_img = (ImageView) content.findViewById(R.id.scan_img);
        AssetNumber = (TextView) content.findViewById(R.id.AssetNumber);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
            upload(scanResult);

        }
    }

    // 开始扫码
    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;

        }
        // 二维码扫码
        Intent intent = new Intent(content, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权0+0
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    private void upload(final String assetNumber) {
        new Thread() {
            @Override
            public void run() {
                try {
                    OkHttpClient client =new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("assetNumber", assetNumber)
                            .build();
                    Request request = new Request.Builder()
                            .url(url)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.i("222", responseData);
                    showResponse(responseData);//解析
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }.start();
    }

    private void showResponse(final String responseData) {
        content.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap bitmap = null;
                    JSONObject json = new JSONObject(responseData);
                    if (json.getString("state").equals("1")) {
                        JSONObject jsonObject = json.getJSONObject("asset");
                        AssetNumber.setText(jsonObject.getString("assetNumber"));
                        AssetName.setText(jsonObject.getString("assetName"));
                        DeptId.setText(jsonObject.getString("deptId"));
                        custodian.setText(jsonObject.getString("userId"));
                        model.setText(jsonObject.getString("model"));
                        Type.setText(jsonObject.getString("type"));
                        odd.setText(jsonObject.getString("company"));
                        status.setText(jsonObject.getString("status"));
                        place.setText(jsonObject.getString("place"));
                        createdate.setText(jsonObject.getString("createdate"));
                        grundlagen.setText(jsonObject.getString("grundlagen"));
                        if (jsonObject.getString("image").equals("")) {
                            InputStream is = getResources().openRawResource(R.mipmap.null_po);
                            bitmap = BitmapFactory.decodeStream(is);
                        } else {
                            byte[] input = Base64.decode(jsonObject.getString("image"), Base64.DEFAULT);
                            bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                        }
                        is_image.setImageBitmap(bitmap);
                    }

                    if (json.getString("state").equals("2")) {
                        Toast.makeText(content, "不存在此资产", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
